import 'package:mobx/mobx.dart';
import 'package:thal/backstage/blueprint/check_in_print.dart';

part 'check_in_room.g.dart';

/// 打卡状态管理
class CheckInRoom = _CheckInRoom with _$CheckInRoom;

abstract class _CheckInRoom with Store {
  /// 所有打卡记录列表
  @observable
  ObservableList<CheckInPrint> checkIns = ObservableList<CheckInPrint>();

  /// 初始化默认打卡数据
  @action
  void initializeDefaultCheckIns() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);

    // 计算本周内的两个日期（今天之前）
    final yesterday = today.subtract(const Duration(days: 1));
    final twoDaysAgo = today.subtract(const Duration(days: 2));

    checkIns = ObservableList<CheckInPrint>.of([
      // admin (id: '1') 的打卡记录
      CheckInPrint(
        id: '1',
        userId: '1', // admin
        checkInDate: yesterday,
        createdAt: DateTime(
          yesterday.year,
          yesterday.month,
          yesterday.day,
          9,
          30,
        ),
      ),
      CheckInPrint(
        id: '2',
        userId: '1', // admin
        checkInDate: twoDaysAgo,
        createdAt: DateTime(
          twoDaysAgo.year,
          twoDaysAgo.month,
          twoDaysAgo.day,
          8,
          45,
        ),
      ),
    ]);
  }

  /// 执行打卡
  @action
  bool performCheckIn(String userId) {
    try {
      final now = DateTime.now();
      final today = DateTime(now.year, now.month, now.day);

      // 检查今天是否已经打卡
      if (hasCheckedInToday(userId)) {
        return false;
      }

      // 创建新的打卡记录
      final newCheckIn = CheckInPrint(
        id: (checkIns.length + 1).toString(),
        userId: userId,
        checkInDate: today,
        createdAt: now,
      );

      checkIns.add(newCheckIn);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 检查今天是否已打卡
  bool hasCheckedInToday(String userId) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);

    return checkIns.any(
      (checkIn) =>
          checkIn.userId == userId &&
          checkIn.checkInDate.year == today.year &&
          checkIn.checkInDate.month == today.month &&
          checkIn.checkInDate.day == today.day,
    );
  }

  /// 检查指定日期是否已打卡
  bool hasCheckedInOnDate(String userId, DateTime date) {
    final targetDate = DateTime(date.year, date.month, date.day);

    return checkIns.any(
      (checkIn) =>
          checkIn.userId == userId &&
          checkIn.checkInDate.year == targetDate.year &&
          checkIn.checkInDate.month == targetDate.month &&
          checkIn.checkInDate.day == targetDate.day,
    );
  }

  /// 获取用户的打卡记录列表
  List<CheckInPrint> fetchUserCheckIns(String userId) {
    return checkIns.where((checkIn) => checkIn.userId == userId).toList()
      ..sort((a, b) => b.checkInDate.compareTo(a.checkInDate)); // 按日期倒序
  }

  /// 获取用户总打卡天数
  int fetchTotalCheckInDays(String userId) {
    return checkIns.where((checkIn) => checkIn.userId == userId).length;
  }

  /// 获取用户本月打卡天数
  int fetchMonthlyCheckInDays(String userId) {
    final now = DateTime.now();
    return checkIns
        .where(
          (checkIn) =>
              checkIn.userId == userId &&
              checkIn.checkInDate.year == now.year &&
              checkIn.checkInDate.month == now.month,
        )
        .length;
  }

  /// 获取用户本周打卡天数
  int fetchWeeklyCheckInDays(String userId) {
    final now = DateTime.now();
    final weekStart = now.subtract(Duration(days: now.weekday - 1));
    final weekEnd = weekStart.add(const Duration(days: 6));

    return checkIns
        .where(
          (checkIn) =>
              checkIn.userId == userId &&
              checkIn.checkInDate.isAfter(
                weekStart.subtract(const Duration(days: 1)),
              ) &&
              checkIn.checkInDate.isBefore(
                weekEnd.add(const Duration(days: 1)),
              ),
        )
        .length;
  }

  /// 获取所有打卡记录
  List<CheckInPrint> fetchAllCheckIns() {
    return List.from(checkIns);
  }

  /// 根据ID获取打卡记录
  CheckInPrint? fetchCheckInById(String checkInId) {
    try {
      return checkIns.firstWhere((checkIn) => checkIn.id == checkInId);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户最近的打卡记录
  CheckInPrint? fetchLatestCheckIn(String userId) {
    final userCheckIns = fetchUserCheckIns(userId);
    return userCheckIns.isNotEmpty ? userCheckIns.first : null;
  }
}
